package com.logansoft.zhxypkoa.repository.sys;

import java.util.List;
import java.util.Optional;

import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.data.rest.core.annotation.RepositoryRestResource;

import com.logansoft.zhxypkoa.domain.sys.Premission;

@RepositoryRestResource(collectionResourceRel = "premissions", path = "premissions")
public interface PremissionRepository extends JpaRepository<Premission, String> {
	// @Query("select p from Premission p where p.roles in (select r from Role r where r.users in (select u from User u where u.username = ?1))")
	@Query("select p from Premission p join fetch p.resource left join p.roles r left join r.users u where u.username = ?1")
	public List<Premission> findListByUsername(String username);

	@Cacheable(value = "premissions", key = "#p0")
	// @Query("select p from Premission p where p.roles in (select r from Role r where r.users in (select u from User u where u.username = ?1))")
	@Query("select p from Premission p join fetch p.resource left join p.roles r left join r.users u, User us where u.id = ?1 or (us.id = ?1 and us.username = 'admin')")
	public List<Premission> findListByUserId(@Param(value = "userId") String userId);
	@Cacheable(value = "premissions", key = "#p0")
	@Override
	Page<Premission> findAll(Pageable pageable);
	@CacheEvict(value = "premissions", key = "#p0.id", allEntries = true)
	@Override
	<S extends Premission> S save(S entity);
	@Cacheable(value = "premissions", key = "#p0")
	@Override
	Optional<Premission> findById(String id);
	@CacheEvict(value = "premissions", key = "#p0", allEntries = true)
	@Override
	void deleteById(String id);
	@CacheEvict(value = "premissions", key = "#p0.id", allEntries = true)
	@Override
	void delete(Premission entity);
}
